package com.bwie.init;

import com.bwie.domain.TProduct;
import com.bwie.mapper.TProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * TODO
 *
 * @Description
 * @Author 36167
 * @Date 2025/3/12 9:59
 **/


@Component
@Slf4j
public class InitDate {

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Autowired
    TProductMapper tProductMapper;

    @PostConstruct
    @Order(1)
    public void start(){
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(TProduct.class);
        boolean exists = indexOps.exists();
        if (!exists){
            indexOps.create();
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);

            log.info("ES索引创建完成");
        }

        List<TProduct> tProducts = tProductMapper.selectList(null);
        for (TProduct tProduct : tProducts) {
            elasticsearchRestTemplate.save(tProduct);

        }
        log.info("ES索引同步完成完成");

    }

}
